import xorEncryptionData from "./Tool/xor";
import httpUtils from "./XmlHttpTool";
import allVariableJs from "./allVariable";
import PlatformUtil from "./PlatformUtil";
import NumberView from "./NumberView";
cc.Class({
    extends: cc.Component,

    properties: {
       
        endAgainGameBtn:cc.Button,
        backGameMapBtn:cc.Button,
        backMarkView:cc.Node,
        closeBtn:cc.Button,
        endSound:{
            default: null,
            type: cc.AudioClip
          },
        endallview:cc.Node,
        bglightcoin:cc.Node,
        bglightNocoin:cc.Node,
        againGame:cc.Button,
        restBtn:cc.Button,
        flag_key:cc.String,
        keysid:cc.String,
        energyCompontent:NumberView,
        videoAd:"",
        showHubProjess:cc.Node,
        SvprogressPrefab: cc.Prefab,
        brannerAdmessage:"",
        gameTopImage:cc.Node
   
    },


    againOnceGameClick:function(){


        if(allVariableJs.haveEnergy==0){

            if(cc.isValid(this.showHubProjess)){
                this.showHubProjess.destroy();
                }
                this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
                this.node.addChild(this.showHubProjess);
                this.showHubProjess.getComponent('SVProgressView').init("体力不足,无法开始游戏")
            
                let finish = cc.callFunc(() => { 
            
                this.showHubProjess.destroy();
            
                }, this);
                let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
                this.showHubProjess.runAction(action);

            return
        }
       
        var changebig = cc.scaleTo(0.2,1.1);

        var finish = cc.callFunc(function(){
    
            var that=this
          var changesmail = cc.scaleTo(0.1,1.0);

          var smaillfinish=cc.callFunc(function(){

            
            that.endallview.active=false

            console.log("重新开始游戏")
    
            cc.director.loadScene("GameSence",function(){
    
                 var mainNode= cc.find("Canvas/backgroundtop")
    
                 mainNode.getComponent("backgrould").onAgainSence();
            
            });

          })

          var seq2 = cc.sequence(changesmail,smaillfinish)
          this.againGame.node.runAction(seq2)
       

       }, this);
    
       var seq = cc.sequence(changebig,finish)
        
       this.againGame.node.runAction(seq)

     

    },

    closeGameClick:function(){

        allVariableJs.allbrannerAD.hide()
        var changebig = cc.scaleTo(0.02,1.2);

        var finish = cc.callFunc(function(){
    
          var changesmail = cc.scaleTo(0.08,1.0);

          var smaillfinish=cc.callFunc(function(){

            cc.director.loadScene("StartGame");

          })

          var seq2 = cc.sequence(changesmail,smaillfinish)
          this.closeBtn.node.runAction(seq2)
       

       }, this);
    
       var seq = cc.sequence(changebig,finish)

       this.closeBtn.node.runAction(seq)

    },

    backGameMapClick:function(){

        console.log("看视频送体力")
        var _this=this
        if(allVariableJs.allvideoAD){

            allVariableJs.allvideoAD.offClose()
            allVariableJs.allvideoAD.offError()
             allVariableJs.allvideoAD.onClose(res => {
            if (res && res.isEnded || res === undefined) {

                 var that=this
                httpUtils.httpPost("/marmot/ads_to_energy",{},function(res){
       
                    console.log("正常播放,可以发游戏奖励",res)
                    var flagstr=res.flag_key+PlatformUtil.platform.params["appver"]
                    var resultstr =xorEncryptionData.encryptionData(flagstr,PlatformUtil.platform.params)
            
                    httpUtils.NhttpPost("/marmot/ads_to_energy",{"flag_key":resultstr,"keysid":res.keysid},function(res){
                      console.log("广告体力请求接口",res)
                      that.energyCompontent.setText(parseInt(res["energy"]))
                      
                  })         
                })   

            } else {
              // 播放中途退出，不下发游戏奖励
              console.log("播放中途退出，不下发游戏奖励",res)
            }
          })

              allVariableJs.allvideoAD.onError((res) => {
                _this.tishifinde()
                 let errcode=res["errCode"] 

                 if(errcode==1004){
                    console.log("无广告资源")
                 }else{
                    console.log("无广告资源")
                 }
              })

              allVariableJs.allvideoAD.load((res) => {
                console.log('激励视频 广告加载成功',res)
       
             })
             .then(() =>allVariableJs.allvideoAD.show())
             .catch(function(err){
                console.log('激励视频抓取结果',err) 
                _this.tishifinde()
             })

        }else{

            var that=this
            let rewardedVideoAd = wx.createRewardedVideoAd({

                adUnitId: 'adunit-8536f460f8a4925c'
            
            })
            allVariableJs.allvideoAD=rewardedVideoAd
            allVariableJs.allvideoAD.offClose()
            allVariableJs.allvideoAD.onClose(res => {
                if (res && res.isEnded || res === undefined) {
    
                     var that=this
                    httpUtils.httpPost("/marmot/ads_to_energy",{},function(res){
           
                        console.log("正常播放,可以发游戏奖励",res)
                        var flagstr=res.flag_key+PlatformUtil.platform.params["appver"]
                        var resultstr =xorEncryptionData.encryptionData(flagstr,PlatformUtil.platform.params)
                
                        httpUtils.NhttpPost("/marmot/ads_to_energy",{"flag_key":resultstr,"keysid":res.keysid},function(res){
                          console.log("广告体力请求接口",res)
                          that.energyCompontent.setText(parseInt(res["energy"]))
                          
                      })         
                    })   
    
                } else {
                  // 播放中途退出，不下发游戏奖励
                  console.log("播放中途退出，不下发游戏奖励",res)
                }
              })

              allVariableJs.allvideoAD.onError((res) => {
          
                 let errcode=res["errCode"] 
                 that.tishifinde()
                 if(errcode==1004){

                    console.log("无广告资源")
                 }else{
                    console.log("无广告资源")

                 }
              })
              allVariableJs.allvideoAD.load((res) => {
                console.log('激励视频 广告加载成功',res)
       
             })
             .then(() =>allVariableJs.allvideoAD.show())
             .catch(function(err){
                console.log('激励视频抓取结果',err) 
                that.tishifinde()
             })
        }
    },

      tishifinde:function(){
   
        if(cc.isValid(this.showHubProjess)){
        this.showHubProjess.destroy();
        }
        this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
        this.node.addChild(this.showHubProjess);
        this.showHubProjess.getComponent('SVProgressView').init("今天的广告已经看完了哦！")
    
        let finish = cc.callFunc(() => { 
    
        this.showHubProjess.destroy();
    
        }, this);
        let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
        this.showHubProjess.runAction(action);
      },

    onLoad () {

         var that =this
       cc.loader.load({url: "https://h5.taoqi001.com/upload/201901/9521c3d601a911bfdc70e0cda4eec30b5bb0ae35.png", type: 'png'}, function (err, img) {
        var mylogo  = new cc.SpriteFrame(img); 
  
        that.gameTopImage.getComponent(cc.Sprite).spriteFrame = mylogo;
      
       });
        this.sendStarHttp();
    
        this.backMarkView.on('touchstart', function (event) {
            console.log("点击结算背景层")
          }, this);

      var that =this
      
      cc.loader.load({url: "https://h5.taoqi001.com/upload/201812/9834e678f3e8c6636778849dd055579c320f0900.png", type: 'png'}, function (err, img) {
        var mylogo  = new cc.SpriteFrame(img); 
        that.bglightcoin.getComponent(cc.Sprite).spriteFrame = mylogo;
        that.bglightcoin.height=432
        that.bglightcoin.width=712

        that.bglightNocoin.getComponent(cc.Sprite).spriteFrame = mylogo;
        that.bglightNocoin.height=432
        that.bglightNocoin.width=712

      });

    },


    sendStarHttp:function(){

        allVariableJs.isPlaying=false

        console.log("结束游戏1",allVariableJs.gameId)
        var hedgehogValue
        if(allVariableJs.hedgehog==true){
          hedgehogValue=1
        }else{
          hedgehogValue=0
        }
        var resultDic={"coins":allVariableJs.wawaCoinAddNumber, "game_id":allVariableJs.gameId, "money":allVariableJs.mouseCoinNum,"stars":allVariableJs.starNumber,"hammers":allVariableJs.chuiziCount,"add_time":allVariableJs.timeCount,"game_time":allVariableJs.myPlayTimes,"hedgehog":hedgehogValue}
        console.log("结束游戏2",hedgehogValue)

        allVariableJs.allbrannerAD.show()

        this.current = cc.audioEngine.play(this.endSound, false, 1);
        
        var resultstr =xorEncryptionData.encryptionData(resultDic,PlatformUtil.platform.params)

          var that=this

         
          
           httpUtils.ThttpPost("/marmot/catch_callback",{"result":resultstr},function(res){

            console.log("上传分数",res)

            let score = allVariableJs.starNumber;
            if (CC_WECHATGAME) {
                console.log("上传排行榜")
                window.wx.postMessage({
                    messageType: 3,
                    MAIN_MENU_NUM: "x1",
                    score: score,
                });
            } else {
                cc.log("提交得分: x1 : " + score)
            }

            // if(allVariableJs.wawaCoinAddNumber==0){
               
            //     if(parseInt(res["data"]["user_stars"])<0){

            //         var starabs=Math.abs(res["data"]["user_stars"])
            //         that.node.getChildByName("gameStarLabel").getChildByName("miusstarNumber").getComponent("NumberView").setLeftText(parseInt(starabs),true)
            //         console.log("星币为负数",starabs)

            //     }else{
            //         that.node.getChildByName("gameStarLabel").getChildByName("starNumberCreator").getComponent("NumberView").setLeftText(parseInt(res["data"]["user_stars"]),false)
            //     }
             
            // }
            // else{
                if(parseInt(res["data"]["user_stars"])<0){
                    
                    var starabs=Math.abs(res["data"]["user_stars"])
                    console.log("星币为负数",starabs)
                    that.node.getChildByName("gameStarLabel").getChildByName("miusstarNumber").getComponent("NumberView").setLeftText(parseInt(starabs),true)
        
                }else{
                    that.node.getChildByName("gameStarLabel").getChildByName("starNumberCreator").getComponent("NumberView").setLeftText(parseInt(res["data"]["user_stars"]),false)
                }     
                console.log("红包金额",res["data"]["money"])
                var money =Math.round((res["data"]["money"]*100))  
                console.log("红包金额2",money)
                that.node.getChildByName("endmoneyArea").getComponent("endmoneyArea").init(money)
            // }

           })

    },

    start () {

    },

    // update (dt) {},
});
